//
//  KABMallSureOrderVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/20.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallSureOrderVC.h"
#import "KABMallShopCartTCell.h"
#import "KABMallShoCarHeaderHFView.h"
#import "KABMallSurOrdFooterHFView.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import "ApiManager.h"
#import "KABModel.h"
#import "GlobalHeader.h"
#import "KABRecAddressVC.h"
#import "UIColor+XDHex.h"
#import "WXApiManager.h"
#import "KABMallMyOrderVC.h"
#import "KABMallOrderDetailVC.h"

@interface KABMallSureOrderVC ()<UITableViewDelegate, UITableViewDataSource, WXApiManagerDelegate>
@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak, nonatomic) IBOutlet UIButton *hAddAddressBtn;
@property (weak, nonatomic) IBOutlet UILabel *hRecNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *hRecPhoneBtn;
@property (weak, nonatomic) IBOutlet UIButton *hRecAddressBtn;

@property (strong, nonatomic) IBOutlet UIView *footerBgView;
@property (weak,   nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@property (strong, readonly) KABReceiverInfoItem *receiverItem;
@property (strong, nonatomic) KABMallShopCartModel *shopModel;

@property (strong, nonatomic) KABMallSubOrdBackModel *tempOrder;

@end

static NSString *const kReuseCellId = @"KABMallShopCartTCell";
static NSString *const kHeaderViewId = @"KABMallShoCarHeaderHFView";
static NSString *const kFooterViewId = @"KABMallSurOrdFooterHFView";

@implementation KABMallSureOrderVC

#pragma mark - life cycle
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActiveHandle:) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"确认订单";
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initSubViews {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerBgViewTapped:)];
    [self.headerBgView addGestureRecognizer:tapGesture];
    
    UINib *headerNib = [UINib nibWithNibName:kHeaderViewId bundle:nil];
    [self.tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:kHeaderViewId];
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    UINib *footerNib = [UINib nibWithNibName:kFooterViewId bundle:nil];
    [self.tableView registerNib:footerNib forHeaderFooterViewReuseIdentifier:kFooterViewId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0;
    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 48.0;
//    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionFooterHeight = 108.0;
    
    self.tableView.tableHeaderView = self.headerBgView;
    self.tableView.tableFooterView = self.footerBgView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.sureBtn addTarget:self action:@selector(sureBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    [self requestReceiverInfoList]; //!< 请求默认地址
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshWholeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.shopModel.sortList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = self.shopModel.sortList[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABMallShopCartTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    NSArray *array = self.shopModel.sortList[indexPath.section];
    [cell configViewWithProDetail:array[indexPath.row] couldSel:NO isEdit:NO];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    KABMallShoCarHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
    NSArray *array = self.shopModel.sortList[section];
    [view configViewWithProDetail:array.firstObject couldSel:NO wholeSel:NO];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    KABMallSurOrdFooterHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kFooterViewId];
    [view configViewWithAttributeString:[self.shopModel desAttributeStrWithIndex:section]];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 0.1;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 56.0;
}

#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvPayResponse:(PayResp *)response {
    NSLog(@"微信支付返回：%d, %@, 响应类型:%d", response.errCode, response.errStr, response.type);
    NSLog(@"微信支付：财付通返回:%@", response.returnKey);
//    [self requestProOrderQueryWithOutTradeNo:self.tempOrder.order_detail.out_trade_no];
}

#pragma mark - event response
- (void)appDidBecomeActiveHandle:(NSNotification *)notification {
    if (self.tempOrder) {;
        NSLog(@"请求微信支付结果");
        // 请求微信支付结果
        [self requestProOrderQueryWithOutTradeNo:self.tempOrder.order_detail.out_trade_no];
    }
}

- (void)headerBgViewTapped:(UIGestureRecognizer *)gesture {
    KABRecAddressVC *selAddVC = [[KABRecAddressVC alloc] init];
    selAddVC.SelectReceiverItem = ^(KABReceiverInfoItem *item) {
        [KABModel sharedInstance].receiverList.selReceiverId = item.receiverId;
        [self refreshWholeView];
    };
    [self showViewController:selAddVC sender:nil];
}
- (void)editBarBtnTapped:(UIBarButtonItem *)item {
}
- (void)sureBtnTapped:(UIButton *)btn {
    // 判断是否选择了收货地址
    if (!self.receiverItem) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择收货地址"];
        return;
    }
    
    // 提示安装微信支付
    if (![WXApi isWXAppInstalled]) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"需要安装微信才能支付"];
        return;
    }
    
    [self requestSubmitOrder];
}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    //    if (self.model.taskList.count >= self.model.totalCount) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    // 可能receiverItem不同于默认地址，但是默认地址为空，一定说明receiverItem为nil
//    if (![KABModel sharedInstance].userInfo.receiver_info) {
//        self.receiverItem = nil;
//    }
    self.hAddAddressBtn.hidden = !!self.receiverItem;
    self.hRecNameLabel.hidden = !self.receiverItem;
    self.hRecPhoneBtn.hidden = !self.receiverItem;
    self.hRecAddressBtn.hidden = !self.receiverItem;
    
    self.hRecNameLabel.text = self.receiverItem.receiver_name;
//    [self.hRecPhoneBtn setTitle:self.receiverItem.receiver_phone forState:UIControlStateNormal];
    NSString *phoneStr = [NSString stringWithFormat:@"   %@", self.receiverItem.receiver_phone];
    [self.hRecPhoneBtn setTitle:phoneStr forState:UIControlStateNormal];
    
    NSString *address = [NSString stringWithFormat:@"   %@ %@ %@", self.receiverItem.province, self.receiverItem.city, self.receiverItem.address];
    [self.hRecAddressBtn setTitle:address forState:UIControlStateNormal];
    
    NSString *titleStr = @"合计：";
    NSString *priceStr = [NSString stringWithFormat:@"%@￥%.2f", titleStr, self.shopModel.wholeSelTotalPrice / 100.0];
    NSMutableAttributedString *mAStr = [[NSMutableAttributedString alloc] initWithString:priceStr];
    NSDictionary *dic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:KABGlobalColorTabBarItemColor],
                          NSFontAttributeName : [UIFont systemFontOfSize:18.0]};
    [mAStr addAttributes:dic range:NSMakeRange(titleStr.length, priceStr.length - titleStr.length)];
    self.totalPriceLabel.attributedText = mAStr;
    
    [self.tableView reloadData];
}

- (void)jumpToOrderDetailOrMyOrder:(KABMallSubOrdBackModel *)backModel paySuc:(BOOL)paySuc {
    UIViewController *vc = nil;
    if (backModel.order_detail.order_list.count == 1) {
        KABMallOrderDetailVC *detailVC = [[KABMallOrderDetailVC alloc] init];
        detailVC.order_id = backModel.order_detail.order_list.firstObject;
        vc = detailVC;
        
    } else if (backModel.order_detail.order_list.count > 1) {
        KABMallMyOrderVC *myOrderVC = [[KABMallMyOrderVC alloc] init];
        if (paySuc) {
            myOrderVC.orderType = KABMallOrderTypeNotSend;
        }
        vc = myOrderVC;
    }
    
    // 清空临时数据
    self.tempOrder = nil;
    
    NSMutableArray *mArray = [self.navigationController.viewControllers mutableCopy];
    [mArray replaceObjectAtIndex:(mArray.count - 1) withObject:vc];
    [self.navigationController setViewControllers:mArray animated:YES];
}

#pragma mark - network request
- (void)requestReceiverInfoList {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiReceiverInfo] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求收货地址返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] receiverListWithDictionary:responseObject];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求收货地址失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestSubmitOrder{
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
    [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    [pars setObject:[self.shopModel submitOrderJsonWithReceiverId:self.receiverItem.receiverId] forKey:@"order_detail"];
    if (self.shoppingcartIdArray) {
        [pars setObject:self.shoppingcartIdArray forKey:@"shoppingcart_id_list"];
    }
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiProductOrder] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"提交订单返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.tempOrder = [KABMallSubOrdBackModel yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self callWx:self.tempOrder.wx_pay];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"提交订单失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestWxPay:(NSObject *)order_list {
    // 请求购物车必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"order_list" : order_list};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiWXPay] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"提交订单返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self callWx:responseObject[KABGlobalJsonKeyResult]];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"提交订单失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

//- (void)callWx:(NSDictionary *)dic {
//    PayReq *request = [[PayReq alloc] init];
//    request.partnerId = dic[@"partnerId"];
//    request.prepayId= dic[@"prepayId"];
//    request.package = dic[@"package"];
//    request.nonceStr= dic[@"nonceStr"];
//    request.timeStamp= [dic[@"timeStamp"] unsignedIntValue];
//    request.sign= dic[@"sign"];
//    NSLog(@"请求参数:\n partnerId = %@ \n prepayId = %@ \n package = %@ \n nonceStr = %@ \n timeStamp = %zd \n sign = %@ ", request.partnerId, request.prepayId, request.package, request.nonceStr, request.timeStamp, request.sign);
//    [WXApi sendReq:request];
//}

- (void)callWx:(KABMallWxPayPars *)wxPay {
    if (!wxPay) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"微信支付参数错误"];
        return;
    }
    
    // 置位代理
    [WXApiManager sharedManager].delegate = self;
    
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = wxPay.partnerId;
    request.prepayId= wxPay.prepayId;
    request.package = wxPay.package;
    request.nonceStr= wxPay.nonceStr;
    request.timeStamp= wxPay.timeStamp;
    request.sign= wxPay.sign;
    NSLog(@"请求参数:\n partnerId = %@ \n prepayId = %@ \n package = %@ \n nonceStr = %@ \n timeStamp = %zd \n sign = %@ ", request.partnerId, request.prepayId, request.package, request.nonceStr, request.timeStamp, request.sign);
    [WXApi sendReq:request];
}

- (void)requestProOrderQueryWithOutTradeNo:(NSString *)out_trade_no {
    // 查询购买结果必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    if (!out_trade_no.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"订单号错误"];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"out_trade_no" : out_trade_no};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiProductOrderQuery] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"查询结果返回：%@", responseObject);
        [hud hideAnimated:NO];
        NSString *str = responseObject[KABGlobalJsonKeyMsg];
        BOOL paySuc = NO;
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            NSDictionary *dic = responseObject[KABGlobalJsonKeyResult];
            str = ([dic[@"result_code"] integerValue] == 1) ? @"支付成功" : @"支付失败";
            paySuc = ([dic[@"result_code"] integerValue] == 1) ? YES : NO;
        }
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:str];
        temp.completionBlock = ^(){
            [self jumpToOrderDetailOrMyOrder:self.tempOrder paySuc:paySuc];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"查询结果失败：%@", error);
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
        temp.completionBlock = ^(){
            [self jumpToOrderDetailOrMyOrder:self.tempOrder paySuc:NO];
        };
    }];
}

#pragma mark - getters and setters
- (KABReceiverInfoItem *)receiverItem {
    return [KABModel sharedInstance].receiverList.selReceiverInfoItem;
}

- (KABMallShopCartModel *)shopModel {
    if (!_shopModel) {
        _shopModel = [[KABMallShopCartModel alloc] init];
        _shopModel.product_list = [self.productArray mutableCopy];
        [_shopModel sortWithSameShop];
    }
    return _shopModel;
}

@end
